<!--
 * @Description:
 * @FilePath: \rs_wms_pc\src\views\invoice\modulationInBill\index.vue
-->
<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" @submit.native.prevent v-show="showSearch" label-width="68px">
        <el-form-item label="单据编号" prop="bizNo">
          <el-input
            v-model="queryParams.bizNo"
            placeholder="请输入单据编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态">
              <el-option v-for="dict in dict.type.in_order_status" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t("search") }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t("reset") }}</el-button>
        </el-form-item>
      </el-form>

      <el-row :gutter="10" class="mb8" ref="btnGroup">
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            plain-->
<!--            icon="el-icon-plus"-->
<!--            size="mini"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['bill:modulationInBill:add']"-->
<!--          >{{ $t("add") }}</el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="success"-->
<!--            plain-->
<!--            icon="el-icon-edit"-->
<!--            size="mini"-->
<!--            :disabled="single||selection[0].status !== 1"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['bill:modulationInBill:edit']"-->
<!--          >{{ $t("edit") }}</el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="danger"-->
<!--            plain-->
<!--            icon="el-icon-delete"-->
<!--            size="mini"-->
<!--            :disabled="multiple"-->
<!--            @click="handleDelete"-->
<!--            v-hasPermi="['bill:modulationInBill:remove']"-->
<!--          >{{ $t("delete") }}</el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="warning"-->
<!--            plain-->
<!--            icon="el-icon-download"-->
<!--            size="mini"-->
<!--            @click="handleImport"-->
<!--            v-hasPermi="['bill:modulationInBill:import']"-->
<!--          >{{ $t("import") }}</el-button>-->
<!--        </el-col>-->
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['bill:modulationInBill:export']"
          >{{ $t("export") }}</el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>

      <el-table ref="table" :height="calcTableHeight" v-loading="loading" :data="modulationInBillList" @selection-change="handleSelectionChange" highlight-current-row >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="50" />
        <af-table-column label="单据编号" align="center" prop="bizNo" >
          <template slot-scope="scope">
            <span class="link-pop"  @click="rowSelection(scope.row)">{{ scope.row.bizNo }}</span>
          </template>
        </af-table-column>
        <af-table-column label="单据状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.in_order_status" :value="scope.row.status" />
          </template>
        </af-table-column>
        <af-table-column label="仓库" align="center" prop="stockCode" />
        <af-table-column label="货主" align="center" prop="owner" />
        <af-table-column label="库存状态" align="center" prop="stockStatus">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.erp_stock_status" :value="scope.row.stockStatus" />
          </template>
        </af-table-column>
        <el-table-column :label="$t('createUser')" align="center" prop="createBy" min-width="100" />
        <el-table-column :label="$t('createTime')" align="center" prop="createTime" min-width="152" />
        <el-table-column :label="$t('updateUser')" align="center" prop="updateBy" min-width="100" />
        <el-table-column :label="$t('updateTime')" align="center" prop="updateTime" min-width="152" />
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

        <!--   单据明细 -->
      <!-- <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
        <el-tab-pane label="入库调整单明细" name="detailList">
          <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
        </el-tab-pane>
        <el-tab-pane label="入库调整记录" name="receive">
          <billDetailList ref="billDetailList" style="padding: unset" :orderData="orderData" />
        </el-tab-pane>
      </el-tabs> -->

      <!-- 添加或修改调拨出库单对话框 -->
      <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
            <el-form-item label="单据号" prop="bizNo">
            <el-input v-model.trim="form.bizNo" placeholder="请输入单据号" />
          </el-form-item>
          <el-form-item label="仓库" prop="stockCode">
            <el-input v-model.trim="form.stockCode" placeholder="请输入仓库" />
          </el-form-item>
          <el-form-item label="货主" prop="owner">
            <el-input v-model="form.owner" placeholder="请输入货主" />
          </el-form-item>
          <el-form-item label="库存状态" prop="stockStatus">
            <el-select style="width:100%;"  v-model="form.stockStatus" placeholder="请输入库存状态"  >
              <el-option
                v-for="dict in dict.type.erp_stock_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">{{ $t("sure") }}</el-button>
          <el-button @click="cancel">{{ $t("cancel") }}</el-button>
        </div>
      </el-dialog>

      <!-- 用户导入对话框 -->
      <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
        <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            {{ $t("importTip1") }}<em>{{ $t("clickUpload") }}</em>
          </div>
          <div class="el-upload__tip text-center" slot="tip">
            <!--          <div class="el-upload__tip" slot="tip">-->
            <!--            <el-checkbox v-model="upload.updateSupport" /> 是否更新已经存在的用户数据-->
            <!--          </div>-->
            <span>{{ $t("importTip") }}</span>
            <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">{{ $t("download") }}</el-link>
          </div>
        </el-upload>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitFileForm">{{ $t("sure") }}</el-button>
          <el-button @click="upload.open = false">{{ $t("cancel") }}</el-button>
        </div>
      </el-dialog>


    <!-- 明细弹窗 -->
    <el-dialog :title="'明细'" :visible.sync="detailModal" width="1000px" append-to-body>
      <el-tabs v-model="activeTab" @tab-click="handleTabClick" type="card" ref="halfTable" class="half-table">
        <el-tab-pane label="入库调整单明细" name="arrival">
          <detailPage ref="detailPage" style="padding: unset" :orderData="orderData" />
        </el-tab-pane>
        <el-tab-pane label="入库调整记录" name="receive">
          <billDetailList ref="billDetailList" style="padding: unset" :orderData="orderData" />
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailModal = false">关 闭</el-button>
      </div>
    </el-dialog>

    </div>
  </template>

  <script>
  import { mixins } from "@/mixin/pageSearchTable";
  import { listModulationInBill, getModulationInBill, delModulationInBill, addModulationInBill, updateModulationInBill} from "@/api/invoice/modulationInBill";
  import { listCustomer } from "@/api/basic/customer";
  import { getToken } from "@/utils/auth"
  import detailPage from "./detail"
  import billDetailList from "./billDetailList"
  import { defaultPageConfig } from "@/const/index";

  export default {
    name: "ModulationInBill",
    dicts: ["in_order_status","erp_stock_status"],
    mixins:[mixins],
    components: { detailPage ,billDetailList},
    provide() {
      return {
        refresh:this.getList
      }
    },
    data() {
      return {
        detailModal: false,
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        selection:[],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 调拨出库单表格数据
        modulationInBillList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          bizNo: null,
          status:null
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          bizNo: [
            { required: true, message: "单据号不能为空", trigger: "blur" }
          ],
          stockCode: [
            { required: true, message: "仓库不能为空", trigger: "blur" }
          ],
          owner: [
            { required: true, message: "货主不能为空", trigger: "blur" }
          ],
        },
        // 导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的物料数据
          updateSupport: 0,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: process.env.VUE_APP_BASE_API + "/bill/modulationInBill/importExcel",
        },
        //页面下方明细的选项
        activeTab:'detailList',
        // 客户列表
        customerList: [],
        orderData:[]
      };
    },
    created() {
      this.getListCustomer();
      this.getList();
    },
    methods: {
      handleTabClick(value){
        console.log(value)
      },
      // 获取客户列表
      getListCustomer(){
        listCustomer({pageNum:1,pageSize:0}).then(response => {
          this.customerList = response.rows;
        });
      },
      //行选择
      rowSelection(row) {
        // this.orderData = row
        this.detailModal = true
        this.$nextTick(() => {
          this.activeTab = "arrival"
          this.orderData = row
        })
      },
      /** 导入按钮操作 */
      handleImport() {
        this.upload.title = "入库调整单导入"
        this.upload.open = true
      },
      /** 下载模板操作 */
      importTemplate() {
        this.download("bill/adjustOut/importTemplate", {}, `入库调整单模板.xlsx`)
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
        this.upload.isUploading = true
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false
        this.upload.isUploading = false
        this.$refs.upload.clearFiles()
        this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true })
        this.getList()
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit()
      },
      /** 查询调拨出库单列表 */
      getList() {
        this.loading = true;
        let params = {
        ...this.queryParams,
        ...defaultPageConfig
      }

        listModulationInBill(params).then(response => {
          let orderData = {...this.orderData}
          this.modulationInBillList = response.rows;
          this.total = response.total;
          this.loading = false;
          this.$nextTick(()=>{
            if(orderData && orderData.id){
              let row = response.rows.find(item => item.id == orderData.id)
              this.$refs.table.setCurrentRow(row);
            }
          })
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          no: null,
          totalQty: null,
          status: 0,
          completeTime: null,
          address: null,
          concat: null,
          remark: null,
          createBy: null,
          updateBy: null,
          updateTime: null,
          createTime: null,
          delFlag: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        // this.rowSelection({});
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.selection = selection
        this.single = selection.length!==1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加入库调整单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getModulationInBill(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改入库调整单";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateModulationInBill(this.form).then(response => {
                this.$modal.msgSuccess(this.$t("editSuc"))
                this.open = false;
                this.getList();
              });
            } else {
              addModulationInBill(this.form).then(response => {
                this.$modal.msgSuccess(this.$t("addSuc"))
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$modal.confirm(this.$t('deleteTip', { num: ids.length })).then(function() {
          return delModulationInBill(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(this.$t("deleteSuc"))
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('bill/modulationInBill/export', {
          ids: this.ids,
          ...this.queryParams
        }, `入库调整单_${new Date().getTime()}.xlsx`)
      }
    }
  };
  </script>
